package com.kaishengit.demo.thread;

public class EnergySystem {

    private int[] energyBoxes;
    private final Object lockObj = new Object();

    public EnergySystem(int n,int initialEnergy){

        energyBoxes = new int[n];
        for (int i=0;i<energyBoxes.length;i++){
            energyBoxes[i] = initialEnergy;
        }
    }

    public void transfer(int from,int to,int amount){

        synchronized (lockObj){

            if (energyBoxes[from]<amount){
                return;
            }
            String t = Thread.currentThread().getName();
            energyBoxes[from] = energyBoxes[from]-amount;
            System.out.println(t+"从"+from+"转移"+amount+"单位能量到"+to);
            energyBoxes[to] = energyBoxes[to]+amount;
            System.out.println(t+"能量总和："+getTotalEnergies());

        }


    }

    public int getTotalEnergies() {

        int sum = 0;
        for (int amount:energyBoxes){
            sum = sum+amount;
        }
        return sum;
    }

    public int getBoxAmount(){
        return energyBoxes.length;
    }


    public static void main(String[] args) {

        EnergySystem energySystem = new EnergySystem(100,1000);
        for (int i=0;i<10;i++){
            EnergyTransferTask energyTransferTask = new EnergyTransferTask(energySystem,i,1000);
            Thread thread = new Thread(energyTransferTask,"Thread_"+i);
            thread.start();
        }
    }

}
